<script setup>
import { Chart } from '@antv/g2'
import dayjs from 'dayjs'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  ready: {
    type: Boolean,
    default: false,
  },
})

let chartInstance = null
const chartDomRef = ref(null)

const state = reactive({
  isInited: false,
})

// 初始化渲染图表
const createChartView = (container, { height }) => {
  const chart = new Chart({
    container,
    autoFit: true,
    height: height || 138,
    marginLeft: -12,
    marginTop: -6,
  })

  const formattedChartData = []

  const lastestDate = props.data.chartData[0]?.date, year = dayjs(lastestDate).year()
  for (let i = 0; i < 10; i++) {
    const date = dayjs(lastestDate).subtract(i, 'day').format('MM-DD')
    const average = props.data.chartData.find(item => item.date === `${year}-${date}`)?.average || 0
    formattedChartData.unshift({ date, average: Number(average) })
  }

  chart
    .data(formattedChartData)
    .encode('x', 'date')
    .encode('y', 'average')
    .scale('x', {
      range: [0, 1],
    })
    .scale('y', {
      nice: true,
    })
    .axis('x', {
      title: false,
    })
    .axis('y', {
      title: props.data.label + props.data.unit,
      titleTextAlign: 'start',
      textStyle: {
        textAlign: 'left',
      },
    })
    .title({
      subtitle: false,
      size: 12,
    })
    .theme({ type: 'custom' })

  chart.line().encode('shape', 'smooth')
    .tooltip({
      items: [{ name: props.data.label, channel: 'y' }],
    })
    .style({
      lineWidth: 3,
      stroke: '#FFD15C',
    }).animate({
      enter: {
        type: 'scaleInX',
        duration: 300,
        delay: 100,
      },
    })
  chart.render()

  state.isInited = true

  return chart
}

// 更新图表数据
const updateChartView = (chart) => {
  const formattedChartData = []

  const lastestDate = props.data.chartData[0]?.date, year = dayjs(lastestDate).year()
  for (let i = 0; i < 10; i++) {
    const date = dayjs(lastestDate).subtract(i, 'day').format('MM-DD')
    const average = props.data.chartData.find(item => item.date === `${year}-${date}`)?.average || 0
    formattedChartData.unshift({ date, average: Number(average) })
  }
  chart.changeData(formattedChartData)

  // 重新渲染
  chart.render()
}

watch([() => props.data, () => props.ready], ([newData, newReady]) => {
  if(state.isInited && chartInstance) {
    // 已经初始化过图表, 直接更新数据
    // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '更新图表数据', newData)
    updateChartView(chartInstance)
  }
  else {
    // 查看数据接口是否已经准备好
    if(props.ready || newReady) {
      if(newData?.chartData && chartDomRef.value) {
        // 请求数据成功, 初始化图表
        const { width, height } = chartDomRef.value.getBoundingClientRect()
        chartInstance = createChartView(chartDomRef.value, { width, height })
        // console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '初始化图表', newData, chartDomRef.value.getBoundingClientRect())
      }
      else {
        // 图标数据为空，更新初始化状态, 展示缺省空状态
        state.isInited = true
        // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '图表数据为空')
      }
    }
    else {
      // console.log('%c%s', 'font-size:2em;background: #DD5644;color: #FFF', '等待数据请求完成', newData)
    }
  }
}, { deep: true, immediate: true })
</script>

<template>
  <section class="chartDomWrap">
    <div ref="chartDomRef" class="panel-layout panel-layout--chart" />
  </section>
</template>

<style lang='scss' scoped>
.chartDomWrap {
  height: 25%;
  padding-top: 10px;
}

.panel-layout {
  &--chart {
    display: flex;
    width: 100%;
    height: 100%;
  }
}
</style>
